package c4.application.transactions;

import c4.application.transactions.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CorporateDatabase implements Resource {

	private Statement stmt = null;
	
	public CorporateDatabase() {
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/corporate?" + 
            											  "user=c4_user&password=p@ssw0rd");

			stmt = conn.createStatement();
		}
		catch (SQLException ex) {
		    // handle any errors
		    System.out.println("SQLException: " + ex.getMessage());
		    System.out.println("SQLState: " + ex.getSQLState());
		    System.out.println("VendorError: " + ex.getErrorCode());
		}
		catch (Exception e) {
			System.out.println("Could not load database driver");
			System.out.println(e);
		}
	}
	
	public ResultSet executeQuery(String query) {
		ResultSet rs = null;
		
		try {
			rs = stmt.executeQuery(query);
		}
		catch (SQLException ex) {
		    // handle any errors
		    System.out.println("SQLException: " + ex.getMessage());
		    System.out.println("SQLState: " + ex.getSQLState());
		    System.out.println("VendorError: " + ex.getErrorCode());
		}
		
		return rs;
	}
	
	public boolean execute(String query) {
		boolean result = true;
		
		try {
			stmt.execute(query);
		}
		catch (SQLException ex) {
			result = false;
			System.err.println(ex);
		}

		return result;
	}
}
